# -*- coding: utf-8 -*-
"""
API 路由定义

@author: AI Assistant
"""
from fastapi import APIRouter, HTTPException
from loguru import logger
import sys
from pathlib import Path

sys_root = Path(__file__).resolve().parent.parent
if str(sys_root) not in sys.path:
    sys.path.insert(0, str(sys_root))

from models.request_models import SessionQueryRequest, ChatRequest
from models.response_models import SessionDataResponse, ChatResponse, ErrorResponse
from services.session_service import SessionService
from services.conversation_service import ConversationManager

# 创建路由器
router = APIRouter(prefix="/api/llm", tags=["LLM服务"])

# 初始化服务
session_service = SessionService()
conversation_manager = ConversationManager()


@router.post("/session/load", response_model=SessionDataResponse, summary="加载会话数据")
async def load_session(request: SessionQueryRequest):
    """加载会话初始参数"""
    try:
        session = session_service.get_session_by_id(request.session_id)
        
        if session:
            return SessionDataResponse(
                success=True,
                message=f"成功加载会话数据",
                data=session.model_dump()
            )
        else:
            return SessionDataResponse(
                success=False,
                message=f"未找到会话: {request.session_id}",
                data=None
            )
    except Exception as e:
        logger.error(f"加载会话失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"加载会话失败: {str(e)}")


@router.post("/chat", response_model=ChatResponse, summary="发送消息并获取LLM响应")
async def chat(request: ChatRequest):
    """发送消息，获取 LLM 响应和参数建议"""
    try:
        result = conversation_manager.continue_conversation(
            session_id=request.session_id,
            user_message=request.message,
            conversation_id=request.conversation_id
        )
        
        if not result or not result.get("success"):
            return ChatResponse(
                success=False,
                message=result.get("message", "对话失败") if result else "对话失败",
                conversation_id=request.conversation_id or "",
                understood=False,
                parameter_changes=None,
                explanation=None,
                current_parameters=None,
                validation_errors=None
            )
        
        # 转换 validation_errors 为字符串列表
        validation_errors = result.get("validation_errors")
        if validation_errors and isinstance(validation_errors, list):
            # 如果是字典列表，转换为字符串列表
            if validation_errors and isinstance(validation_errors[0], dict):
                validation_errors = [
                    f"{err.get('parameter', 'unknown')}: {err.get('message', 'unknown error')}"
                    for err in validation_errors
                ]
        
        # 提取更新结果
        update_result = result.get("update_result")
        
        return ChatResponse(
            success=True,
            message=result["message"],
            conversation_id=result["conversation_id"],
            understood=result.get("understood", False),
            intent_type=result.get("intent_type"),
            parameter_changes=result.get("parameter_changes"),
            explanation=result.get("explanation"),
            current_parameters=result.get("current_parameters"),
            validation_errors=validation_errors,
            update_success=update_result.get("success") if update_result else None,
            update_message=update_result.get("message") if update_result else None,
            update_data=update_result.get("data") if update_result else None,
            parameter_ranges=result.get("parameter_ranges"),
            rainfall_simulation=result.get("rainfall_simulation")
        )
        
    except Exception as e:
        # 使用 repr() 避免 logger 格式化错误
        error_msg = repr(str(e))
        logger.error(f"对话失败: {error_msg}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"对话失败: {str(e)}")


@router.get("/conversation/{conversation_id}", summary="获取对话历史")
async def get_conversation_history(conversation_id: str):
    """获取对话历史"""
    try:
        history = conversation_manager.get_conversation_history(conversation_id)
        
        if history is None:
            return {
                "success": False,
                "message": "获取对话历史失败",
                "conversation_id": conversation_id,
                "history": [],
                "total_count": 0
            }
        
        return {
            "success": True,
            "message": "成功获取对话历史",
            "conversation_id": conversation_id,
            "history": history,
            "total_count": len(history)
        }
        
    except Exception as e:
        logger.error(f"获取对话历史失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取对话历史失败: {str(e)}")


@router.get("/health", summary="健康检查")
async def health_check():
    """健康检查接口"""
    return {
        "status": "healthy",
        "service": "LLM Service",
        "version": "1.0.0"
    }

